package cn.b.sky.common.file;

import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 
 * <strong>Title : ImageModel.java<br></strong>
 * <strong>Package : cn.b.sky..utils.file.excel<br></strong>
 * <strong>Description : </strong>图片模型，计算该图片占据了多少行多少列<br> 
 * <strong>Create on : 2016-4-22 下午5:15:25<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class ImageModel implements ExcelModel {

  private static final Logger log = LoggerFactory.getLogger(ImageModel.class);

  // 一英寸=72磅=25.4毫米=1440缇
  // 一磅=0.353毫米=20缇
  // excel行高单位为磅
  /* private static int dpi=96; */// dpi：一英寸可显示的像素点个数 通常电脑 dpi=96
  private final String imgData;

  private Excel excel;

  public ImageModel(String imgData) {
    this.imgData = imgData;
  }

  @Override
  public String type() {
    return ExcelUtil.IMAGE;
  }

  @Override
  public void setExcel(Excel excel) {
    this.excel = excel;
  }

  @Override
  public Point insert(Point start) {
    if (imgData == null || this.imgData.length() == 0) {
      return start;
    }
    HSSFSheet sheet = excel.getSheet();
    HSSFWorkbook workBook = excel.getWorkwork();
    return addImage(imgData, workBook, sheet, start);
  }

  public static byte[] decodeDataUrl(String imgData) {
    String encodingPrefix = "base64,";
    int contentStartIndex = imgData.indexOf(encodingPrefix) + encodingPrefix.length();
    return Base64.decodeBase64(imgData.substring(contentStartIndex));
  }

  public Point addImage(String imgData, HSSFWorkbook wb, HSSFSheet sheet, Point start) {
    int startCol = start.getCol();
    int startRow = start.getRow();
    byte[] bytes = decodeDataUrl(imgData);
    ByteArrayInputStream byteArrayIn = new ByteArrayInputStream(bytes);
    ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
    BufferedImage bufferImg = null;
    HSSFClientAnchor anchor = null;
    try {
      bufferImg = ImageIO.read(byteArrayIn);
      ImageIO.write(bufferImg, "png", byteArrayOut);
      // 画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
      HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
      if (patriarch == null) {
        patriarch = sheet.createDrawingPatriarch();
      }
      // anchor主要用于设置图片的位置锚
      anchor = new HSSFClientAnchor(0, 0, 255, 255, (short) startCol, startRow, (short) 0, 0);

      // 插入图片
      HSSFPicture picture = patriarch.createPicture(anchor,
          wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
      picture.setFlipHorizontal(false);
      picture.setFlipVertical(false);
      anchor = picture.getPreferredSize();
      anchor.setAnchorType(2);
      anchor = new HSSFClientAnchor(anchor.getDx1(), anchor.getDy1(), anchor.getDx2(), anchor.getDy2(),
          (short) (startCol + anchor.getCol1()), startRow + anchor.getRow1(), (short) (startCol + anchor.getCol2()),
          startRow + anchor.getRow2());
      picture.setAnchor(anchor);
      excel.getPictures().add(picture);
    } catch (IOException e) {
      log.error("{}", e);
    }
    return new Point(anchor.getCol2() + 1, anchor.getRow2() + 1);

  }

}
